package net.yxsoft.service;

import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import net.yxsoft.kit.Helper;
import net.yxsoft.model.Area;
import net.yxsoft.resource.SqlRes;
import rapid.core.TResult;
import rapid.jfinal.BaseService;
import rapid.util.StrKit;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.List;

/**
 * @author zhaohaibo
 */
public class AreaService extends BaseService {
  public static final AreaService INSTANCE = new AreaService();
  private Area dao = new Area().dao();
  private static final String SQL_NAME = SqlRes.AREA;

  public Page pagingByPcode(String pcode,String areaName, int pageIndex, int pageSize) {
    Kv cond = Kv.by("pcode", pcode);
    if(StrKit.hasValue(areaName)) {
      cond.set("areaName", areaName);
    }
    return paging(SQL_NAME + "findByPcode", cond, pageIndex, pageSize);
  }

  public List<Record> findByPcode(String pcode,String areaName, String excludeCode) {
    Kv cond = Kv.by("pcode", pcode);

    if(StrKit.hasValue(excludeCode)) {
      cond.set("excludeCode", excludeCode);
    }
    if(StrKit.hasValue(areaName)) {
      cond.set("areaName", areaName);
    }
    return Db.find(Db.getSqlPara(SQL_NAME + "findByPcode", cond));
  }

  public List<Record> findByRank(String rank) {

    List<Record> list= Db.find("select * from s_area where attrib_05=? and attrib_04='320000'",rank);

    return list;
  }



  public Area findById(String id) {
    return new Area().findFirst(Db.getSqlPara(SQL_NAME + "findByParentCode", Kv.by("id", id)));
  }

  public TResult add(Area obj) {
    if(obj == null || obj.getConflictId() != null) {
      return fail();
    }

    String shortName = obj.getAttrib03();

    if(Db.findFirst("select * from s_area where attrib_01 = ? or attrib_02 = ?" +
                      (StrKit.hasValue(shortName) ? " or attrib_03 = ?" : " or 1 = ?"),
                    obj.getAttrib01(), obj.getAttrib02(), StrKit.hasValue(shortName) ? shortName : "2") != null) {
      return TResult.fail("记录重复。");
    }

    if(StrKit.isEmpty(obj.getAttrib04())) {
      obj.setAttrib04("0");
    }

    if(StrKit.isEmpty(obj.getAttrib03())) {
      obj.setAttrib03(obj.getAttrib02());
    }

    if(StrKit.isEmpty(obj.getAttrib03())) {
      obj.setAttrib03(obj.getAttrib02());
    }

    if(obj.getAttrib17() == null) {
      obj.setAttrib17(BigDecimal.ZERO);
    }

    obj.setConflictId(Helper.bulidUUID());

    if(obj.save()) {
      return success();
    }

    return fail();
  }

  public TResult update(Area obj) {
    if(obj == null || obj.getConflictId() == null) {
      return fail();
    }

    Area dao = new Area();
    Area old = dao.findById(obj.getConflictId());

    if(old == null) {
      return fail();
    }

    String shortName = obj.getAttrib03();
    if(Db.findFirst("select * from s_area where conflict_id != ? and (attrib_01 = ? or attrib_02 = ?" +
                      (StrKit.hasValue(shortName) ? " or attrib_03 = ?" : " or 1 = ?") + ")",
                    obj.getConflictId(), obj.getAttrib01(), obj.getAttrib02(),
                    StrKit.hasValue(shortName) ? shortName : "2") != null) {
      return TResult.fail("记录重复。");
    }

    old.setAttrib01(obj.getAttrib01());
    old.setAttrib02(obj.getAttrib02());
    old.setAttrib03(obj.getAttrib03());
    old.setAttrib04(StrKit.hasValue(obj.getAttrib04()) ? obj.getAttrib04() : "0");
    old.setAttrib05(obj.getAttrib05());
    old.setAttrib06(obj.getAttrib06());
    old.setAttrib07(obj.getAttrib07());
    old.setAttrib17(obj.getAttrib17() != null ? obj.getAttrib17() : BigDecimal.ZERO);

    if(old.update()) {
      return success();
    }

    return fail();
  }

  public void delete( String id) {
    Db.tx(new IAtom() {
      public boolean run() throws SQLException {
        dao = new Area();
        Area obj = dao.findById(id);
        if(obj != null) {
          deleteByPcode(obj.getAttrib01());
          obj.delete();
        }

        return true;
      }
    });
  }

  public Record findAreas(String c1, String c2, String c3) {
    if(StrKit.hasValue(c1)) {
      Record rd = new Record();
      String sql = "select attrib_01 value, attrib_02 text from s_area where attrib_01 = ?";

      Record temp1 = Db.findFirst(sql, c1);
      if(temp1 != null) {
        rd.set("sf", temp1);

        if(StrKit.hasValue(c2)) {
          Record temp2 = Db.findFirst(sql, c2);
          if(temp2 != null) {
            rd.set("cs", temp2);

          } else {
            return rd;
          }

          if(StrKit.hasValue(c3)) {
            Record temp3 = Db.findFirst(sql, c3);
            if(temp3 != null) {
              rd.set("qx", temp3);
            }
          }

          return rd;

        } else {
          return rd;
        }

      } else {
        return null;
      }
    }

    return null;
  }

  private void deleteByPcode(String pcode) {
    List<Area> objs = dao.find("select * from s_area where attrib_04 = ?", pcode);

    if(objs.size() > 0) {
      for(Area obj : objs) {
        deleteByPcode(obj.getAttrib01());
        obj.delete();
      }
    }
  }

  public static final String areaCodeCache = "powerArea";  //万能导入缓存

  public List<Record> getAreaByLevelcode(String levelCode) {
    List<Record> objs = Db.findByCache(areaCodeCache,levelCode,"select a.*,'area' as tag from s_area a where attrib_05 = ?", levelCode);

    return objs;
  }

}
